#!/usr/bin/perl

$listfile = $ARGV[0];
$numgames = $ARGV[1];
$timeout = $ARGV[2];
$gametype = $ARGV[3];

@teams=();
%classes=();
%scores=();
%setsremaining=();
$numteams = 0;

open(IN, "< $listfile");
while(<IN>) {
	chomp;
	if(/,/ && !/^#/) {
		($teamname, $classname) = split(/,/);
		$teams[$numteams++] = $teamname;
		$classes{$teamname} = $classname;
	}
}
close(IN);

for($i=0; $i<$numteams; $i++) {
	$setsremaining{$teams[$i]}=$numteams - 1;
}

for($i=0; $i<$numteams; $i++) {
	for($j=$i+1; $j<$numteams; $j++) {
		$teamA = $teams[$i];
		$teamB = $teams[$j];
		$teamAclass = $classes{$teamA};
		$teamBclass = $classes{$teamB};

		print "\nPlaying $teamA against $teamB (group $listfile)\n";

		open(SET, "perl funnyset.pl $teamA $teamAclass $teamB $teamBclass $numgames $timeout $gametype |");
		while(<SET>) {
			chomp;
			print "$_\n";
			if(/RESULT_WIN/) {
				($dummy, $winner) = split(/:/);
				$scores{$winner} += 2;
			} elsif(/RESULT_DRAW/) {
				$scores{$teamA} += 1;
				$scores{$teamB} += 1;
			}
		} 
		close(SET);

		$setsremaining{$teamA}--;
		$setsremaining{$teamB}--;

		print "\nScore (group $listfile)\n";
		for($k=0; $k<$numteams; $k++) {
			$teamname=$teams[$k];
			$teamscore=$scores{$teamname};
			$remaining=$setsremaining{$teamname};
			print "$teamname\t$teamscore\t(remaining $remaining)\n";	
		}
	}
}

for($i=0; $i < $numteams; $i++) {
	for($j=$i+1; $j < $numteams; $j++) {
		if($scores{$teams[$i]} < $scores{$teams[$j]}) {
			$t = $teams[$i];
			$teams[$i] = $teams[$j];
			$teams[$j] = $t;
		}
	}
}

print "\nFinal ranking (group $listfile)\n"; 
for($i=0; $i < $numteams; $i++) {
	$teamname=$teams[$i];
	$teamscore=$scores{$teamname};
	print "$teamname\t$teamscore\n";	

}


